package com.roamer.audition.web.export;

import com.alibaba.excel.EasyExcel;
import com.roamer.audition.common.response.CompanyVO;
import com.roamer.audition.common.service.CompanyService;
import com.roamer.audition.web.export.model.CompanyExcelVO;
import io.netty.util.concurrent.DefaultThreadFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 公司导出
 *
 * @author roamer
 * @version v1.0
 * @date 2019/10/13 00:01
 */
@Slf4j
@Component
public class CompanyExcelService {

    private final CompanyService companyService;

    public CompanyExcelService(CompanyService companyService) {
        this.companyService = companyService;
    }

    public File exportExcel() {
        Long count = companyService.getAllCount();
        List<CompanyVO> companyList = companyService.getCompanyList();
        long startTIme = System.currentTimeMillis();
        EasyExcel.write(new File("/Users/wangshichang/Desktop/aa.xlsx"), CompanyExcelVO.class)
                .sheet()
                .doWrite(companyList);
        log.debug("耗时：" + (System.currentTimeMillis() - startTIme) + "ms");
        long startTIme1 = System.currentTimeMillis();
        EasyExcel.write(new File("/Users/wangshichang/Desktop/aa.csv"), CompanyExcelVO.class)
                .sheet()
                .doWrite(companyList);
        log.debug("耗时：" + (System.currentTimeMillis() - startTIme1) + "ms");

        return null;
    }

    public static final int BATCH_AMOUNT = 100000;
    public static final int MAX_ROW_SHEET = 1000000;

    public void exportExcel2() {
        long beginTime = System.currentTimeMillis();
        long endTime = LocalDateTime.now().withMonth(2).toEpochSecond(ZoneOffset.of("+8"));
        long allCount = companyService.getAllCount();
        long totalPage = allCount % BATCH_AMOUNT == 0 ? allCount / BATCH_AMOUNT : allCount / BATCH_AMOUNT + 1;
        // 查询任务池
        ExecutorService sqlTaskExecutorService =
                Executors.newFixedThreadPool(10, new DefaultThreadFactory("export-pool"));
        List<Future<List<CompanyVO>>> futureList = new ArrayList<>();
        for (int i = 0; i < totalPage; i++) {
            StatisticsTask task = new StatisticsTask(companyService, i, beginTime, endTime);
            sqlTaskExecutorService.submit(task);
        }
        sqlTaskExecutorService.shutdown();
        // 计算
        List<CompanyVO> companyList = companyService.getCompanyList();
    }
}
